package com.whccb.apps.office.document.event;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.commons.database.RowMapper;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.util.ODAppUtil;

import cn.jpush.api.utils.StringUtils;

public class TaskOptionSaveAsFormEvent implements ExecuteListenerInterface {
    public String getDescription() {
        return "收发文流程节点任务离开后，根据FW_TASK_FORM_MAPPING.properties配置文件将留言自动写到BO字段上。";
    }

    public String getProvider() {
        return "ActionSoft";
    }

    public String getVersion() {
        return "AWS 6.0";
    }

    public void execute(ProcessExecutionContext pec) throws Exception {
        String processInstId = pec.getProcessInstance().getId();
        String boName = "";
        Map<String, Object> paramMap = SDK.getProcessAPI()
                .getVariables(processInstId);
        if (paramMap != null && !paramMap.isEmpty()) {
            boName = paramMap.get("BONAME") != null
                    ? paramMap.get("BONAME").toString() : "";
        }
        if (StringUtils.isNotEmpty(boName)) {
            String taskMsg = "";
            String createTime = "";
            List<Map<String, String>> checkList = getCheckList(processInstId,
                    pec.getTaskInstance().getId(),
                    pec.getUserContext().getUID());
            if (checkList != null && !checkList.isEmpty()
                    && checkList.size() > 0) {
                Map<String, String> checkMap = checkList.get(0);
                if (checkMap != null && !checkMap.isEmpty()) {
                    taskMsg = checkMap.get("MSG");
                    String createDateTime = checkMap.get("CREATEDATE");
                    if (StringUtils.isNotEmpty(createDateTime)
                            && createDateTime.contains(".")) {
                        createTime = createDateTime.substring(0,
                                createDateTime.lastIndexOf("."));
                    }
                }

            }

            String taskDefId = pec.getTaskInstance().getActivityDefId();
            Properties odMappingProperties = ODAppUtil
                    .getProperties("FW_TASK_FORM_MAPPING.properties");
            String valueStr = getPropertiesValue(odMappingProperties,
                    taskDefId);
            if (valueStr != null && StringUtils.isNotEmpty(valueStr)) {
                String[] values = valueStr.split("&");
                if (values != null && values.length > 1) {
                    String fieldName = values[0];
                    String checkOption = values[1];
                    if (checkOption != null
                            && StringUtils.isNotEmpty(checkOption)) {
                        if (pec.isChoiceActionMenu(checkOption)) {
                            if (fieldName != null
                                    && StringUtils.isNotEmpty(fieldName)) {
                                String oldValue = SDK
                                        .getBOAPI().getByProcess(boName,
                                                processInstId, fieldName)
                                        .toString();
                                // 如果是退回的，则忽略原先意见
                                List<HistoryTaskInstance> taskHisList = SDK
                                        .getHistoryTaskQueryAPI()
                                        .processInstId(processInstId)
                                        .activityDefId(taskDefId)
                                        .addQuery("TASKSTATE !=", "9")
                                        .addQuery("ID !=",
                                                pec.getTaskInstance().getId())
                                        .target(pec.getUserContext().getUID())
                                        .list();
                                if (taskHisList != null
                                        && !taskHisList.isEmpty()
                                        && taskHisList.size() > 0) {
                                    oldValue = "";
                                }
                                // 这里判断是否行领导签发，如果是则将原先分管行领导姓名写于会签HQ第一个
                                if ("obj_c7476ccd8f000001ced31a0e802d3560"
                                        .equals(taskDefId)) {
                                    String hq = SDK.getBOAPI().getByProcess(
                                            boName, processInstId, "HQ") + "";
                                    List<HistoryTaskInstance> fghld = SDK
                                            .getHistoryTaskQueryAPI()
                                            .processInstId(processInstId)
                                            .activityDefId(
                                                    "obj_c7476cc63ac0000122df597914541c1c")
                                            .orderByEndTime().desc().list();
                                    if (fghld != null && !fghld.isEmpty()
                                            && fghld.size() > 0) {
                                        String fgid = fghld.get(0).getTarget();
                                        if (org.apache.commons.lang.StringUtils
                                                .isBlank(hq)) {
                                            hq = UserCache.getModel(fgid)
                                                    .getUserName();
                                        } else {
                                            hq = UserCache.getModel(fgid)
                                                    .getUserName() + "," + hq;
                                        }
                                    }
                                    SDK.getBOAPI().updateByBindId(boName,
                                            processInstId, "HQ", hq);
                                }
                                SDK.getBOAPI().updateByBindId(boName,
                                        processInstId, fieldName,
                                        getTaskMsg(pec.getUserContext(),
                                                oldValue, taskMsg, createTime));

                            }
                        }
                    }

                }
            }

        }
    }

    private List<Map<String, String>> getCheckList(String bindid, String taskid,
            String uid) {
        String querySql = " SELECT a.CREATEUSER,a.CREATEDATE,a.ACTIONNAME,a.MSG FROM WFC_COMMENT a WHERE a.PROCESSINSTID = :PROCESSINSTID AND a.TASKINSTID = :TASKINSTID AND a.CREATEUSER = :CREATEUSER ORDER BY CREATEDATE DESC ";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("PROCESSINSTID", bindid);
        paramMap.put("TASKINSTID", taskid);
        paramMap.put("CREATEUSER", uid);
        return DBSql.query(querySql, paramMap,
                new RowMapper<Map<String, String>>() {
                    public Map<String, String> mapRow(ResultSet rs, int index)
                            throws SQLException {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("CREATEUSER", rs.getString("CREATEUSER"));
                        map.put("CREATEDATE", rs.getString("CREATEDATE"));
                        map.put("ACTIONNAME", rs.getString("ACTIONNAME"));
                        map.put("MSG", rs.getString("MSG"));
                        return map;
                    }

                });
    }

    private String getPropertiesValue(Properties pro, String name) {
        String value = "";
        if (pro != null && !pro.isEmpty()) {
            try {
                value = pro.getProperty(name);
            } catch (Exception e) {

            }
        }
        return value;
    }

    private String getTaskMsg(UserContext me, String oldValue, String msg,
            String createTime) {
        StringBuffer result = new StringBuffer();
        // if (oldValue != null && StringUtils.isNotEmpty(oldValue)) {
        // result.append(oldValue);
        // result.append("\r\n").append("\r\n");
        // }
        String userName = me.getUserName();
        if (org.apache.commons.lang.StringUtils.isBlank(msg)) {
            msg = "同意";
        }
        if (org.apache.commons.lang.StringUtils.isBlank(createTime)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            createTime = sdf.format(new Date());
        }
        result.append(" \r\n");
        result.append("  ");
        result.append(msg);
        result.append("\r\n").append("\r\n");
        result.append("    ").append(userName).append("\r\n")
                .append("\r\n").append("  " + createTime);

        return result.toString();
    }
}
